var ih = 906;
var iw = 546;
var icount = 80
// var ih = 820;
// var iw = 1360;
var ifill = 0;
var isDown = 0;
var wordHeight = 16;
var wordsAnnMap = new Object();
var type = 1;
var OX = 0;
var OY = 0;
var point = function (str, cost, ancount) {
    this.str = str;
    this.cost = cost;
    this.ancount = ancount;
}
var api = "",source="";
var token = $.cookie('token') || ''
$(function () {
  function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = decodeURIComponent(window.location.search).substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return "";
  };
  api = getQueryString('api');
  source = getQueryString('source');
})
function sortPoint(a, b) {
    return parseFloat(b.cost) - parseFloat(a.cost);
}
function base64Encode(str) {
    var CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    var out = "", i = 0, len = str.length, c1, c2, c3;
    while (i < len) {
        c1 = str.charCodeAt(i++) & 0xff;
        if (i == len) {
            out += CHARS.charAt(c1 >> 2);
            out += CHARS.charAt((c1 & 0x3) << 4);
            out += "==";
            break;
        }
        c2 = str.charCodeAt(i++);
        if (i == len) {
            out += CHARS.charAt(c1 >> 2);
            out += CHARS.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
            out += CHARS.charAt((c2 & 0xF) << 2);
            out += "=";
            break;
        }
        c3 = str.charCodeAt(i++);
        out += CHARS.charAt(c1 >> 2);
        out += CHARS.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
        out += CHARS.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
        out += CHARS.charAt(c3 & 0x3F);
    }
    return out;
}
function drawImage(word) {
    // $('#imgdiv').fadeOut('slow');
    OX = 0;
    OY = 0;
    $('#canvas-small-img').fadeOut('slow');

    ih = (parseInt($(window).height()))+"px";
    iw = (parseInt($(window).width()))+"px";
    $('#canvas-bk0').attr('width', iw);
    $('#canvas-bk0').attr('height', ih);
    var ih2 = $('#imgdiv')[0].offsetHeight-40;
    var iw2 = $('#imgdiv')[0].offsetWidth-30;
    $('#canvas-small-img')[0].style.width = iw2 + 'px';
    $('#canvas-small-img')[0].style.height = ih2 + 'px';
    $('#canvas-small').attr('width', iw2);
    $('#canvas-small').attr('height', ih2);
    $.ajax({
        url: "bg-t.jpg",
        type: "GET",
        mimeType: "text/plain; charset=x-user-defined"
    }).done(function (data, textStatus, jqXHR) {
        $("#bk").attr('src', 'data:image/jpeg;base64,' + base64Encode(data));
        $('#bk')[0].onload = function () {
            var sqSeach = '';
            // 如果检索式中有'/'，则不拼接'R/'
            if(word.indexOf('/')>-1){
                sqSeach = word
            }else{
                sqSeach = "R/"+word
            }
            $.ajax({
                type: 'POST',
                contentType: 'application/json;charset=utf-8',
                url: api + 'patent-city/city/patent/map',
                data: JSON.stringify({
                    sf: 'QueryRelatedClusterMap',
                    sx: 'QueryRelatedClusterMap',
                    // iw: '1360',
                    // ih: '600',
                    iw: '1600',
                    ih: '1600',
                    idi: '4',
                    icount: icount,
                    // icount: '128',
                    sq: sqSeach
                }),
                beforeSend: function(request){
                    request.setRequestHeader("Authorization", token)
                },
                success: function (res) {
                    if(res.status==40301){
                        window.parent.vueStatus(res.status)
                        return
                    }
                    var json = res.data.Json
                    ifill = res.data.fill;
                    type = res.data.type;
                    for(let i in json.tag){
                      if(json.tag[i].indexOf(word)>-1){
                        json.tag.splice(i, 1)
                        break
                      }
                    }
                    drawBackGround($('#canvas-bk0')[0].getContext('2d'), json);
                    initWords();
                    var imgData = $('#canvas-bk0')[0].getContext('2d').getImageData((iw - iw2) / 2, (ih - ih2) / 2, iw2, ih2);
                    $('#canvas-small')[0].getContext('2d').putImageData(imgData, 0, 0);
                    $('#canvas-small-img')[0].src = $('#canvas-small')[0].toDataURL('images/png');
                    generateSmallMap((iw - iw2) / 2, (ih - ih2) / 2);
                    OX = (iw - iw2) / 2;
                    OY = (ih - ih2) / 2;
                    // $('#imgdiv').fadeIn('slow');
                    $('#canvas-small-img').fadeIn('slow');
                },
                dataType: 'json'
            });
        };

    });

}
var x0 = 0;
var y0 = 0;
var x1 = 0;
var y1 = 0;
var x2 = 0;
var y2 = 0;
var zx1 = 0;
var zy1 = 0;
var cx1 = 0;
var cy1 = 0;

function mousedown(e) {
    isDown = 1;
    $('#canvas-small-img').css('cursor', 'move');
    x0 = e.layerX;
    y0 = e.layerY;


    e.preventDefault(); // 取消事件默认行为

    //stopImmediatePropagation(); // 取消事件冒泡同时阻止当前节点上的事件处理程序被调用。

    //stopPropagation(); // 取消事件冒泡对当前节点无影响。
    // var ih2 = $('#imgdiv')[0].offsetHeight;
    // var iw2 = $('#imgdiv')[0].offsetWidth;
    // var imgData = $('#canvas-bk0')[0].getContext('2d').getImageData((iw-iw2)/2-cx1, (ih-ih2)/2-cy1, iw2, ih2);
    // $('#canvas-small')[0].getContext('2d').putImageData(imgData, 0, 0);

}
function mouseup(e) {
    isDown = 0;
    $('#canvas-small-img').css('cursor', 'default');
    x1 = e.layerX;
    y1 = e.layerY;
    zx1 += x1 - x0;
    zy1 += y1 - y0;
    // var ih2 = $('#imgdiv')[0].offsetHeight;
    //  var iw2 = $('#imgdiv')[0].offsetWidth;
    //  var imgData = $('#canvas-bk0')[0].getContext('2d').getImageData((iw-iw2)/2-cx1, (ih-ih2)/2-cy1, iw2, ih2);
    //  $('#canvas-small')[0].getContext('2d').putImageData(imgData, 0, 0);

}
function generateSmallMap(x, y) {
    $('#map-small').empty();
    $('area').each(function () {
        var coords = $(this).attr('coords').split(',');
        var cx = parseFloat(coords[0]) - x;
        var cy = parseFloat(coords[1]) - y;
        if (cx >= 0 && cy >= 0) {
            $('#map-small').append($('<area shape="rect" coords="' + cx + ',' + cy + ',' + (parseFloat(coords[2]) - x) + ',' + (parseFloat(coords[3]) - y) + '" href ="sun.html" alt="' + $(this).attr('alt') + '" title="' + $(this).attr('title') + '"/>'));
        }
    });
    $("#map-small").attr('x', x);
    $("#map-small").attr('y', y);
    $("#map-small area").on("click", function (e) {
        e.preventDefault();
        // $('#input_search')[0].value = $(this).attr('title');
        // $('#btn_search').click();
        var keywords =  $(this).attr('title');
        // top.location="./newslist.html?keywords="+encodeURI(encodeURI(keywords));
        // top.location="./newslist.html?keywords="+keywords;
    });
}
function mousemove(e) {
    if (isDown == 1) {
        var ih2 = $('#imgdiv')[0].offsetHeight;
        var iw2 = $('#imgdiv')[0].offsetWidth;


        x2 = e.layerX;
        y2 = e.layerY;

        cx1 = x2 + zx1 - x0;
        cy1 = y2 + zy1 - y0;
        var cx = (iw - iw2) / 2 - cx1;
        var cy = (ih - ih2) / 2 - cy1;
        if (cx < 0)
            cx = 0;
        if (cy < 0)
            cy = 0;
        if (cx + iw2 > iw)
            cx = iw - iw2;
        if (cy + ih2 > ih)
            cy = ih - ih2;
        if(iw<iw2)
            cx = OX;
        if (cx != parseInt( $("#map-small").attr('x') ) || cy !=  parseInt($("#map-small").attr('y')) ) {
            var imgData = $('#canvas-bk0')[0].getContext('2d').getImageData(cx, cy, iw2, ih2);
            $('#canvas-small')[0].getContext('2d').putImageData(imgData, 0, 0);
            $('#canvas-small-img')[0].src = $('#canvas-small')[0].toDataURL('images/png');
            generateSmallMap(cx,cy);
        } else {
            return false;
        }

    } else {
        return false;
    }
    // e.preventDefault(); // 取消事件默认行为
}
function initWords() {
    var points = new Array();
    $('.area').each(function () {
        points[points.length] = new point($(this).attr('w'), $(this).attr('c'));
    });
    points.sort(sortPoint);
    var canwords = $('#canvas-bk0')[0];
    var w2d = canwords.getContext('2d');
    /*if (json.length != 0) {
     var bk0 = dojo.byId('canvas-bk0');
     w2d.putImageData(bk0.getContext('2d').getImageData(0, 0, bk0.width, bk0.height), 0, 0);
     }*/

    w2d.font = "12px verdana,Arial,Helvetica,sans-serif";
    $('.area').each(function () {
        var txt = $(this).attr('w');
        var u = $(this).attr('u');
        var freq = $(this).attr('c');
        var ax = $(this).attr('ax');
        var ay = parseInt($(this).attr('ay'));
        var ac = $(this).attr('ac');
        w2d.lineWidth = 2;
        w2d.beginPath();
        w2d.strokeStyle = ac;
        w2d.arc(ax, ay + 4.0, 2.0, 0, Math.PI * 2, true);
        w2d.stroke();
        w2d.fillStyle = 'white';
        w2d.fill();
        w2d.closePath();

        var coors = $(this).attr('coords').split(',');
        var left = parseInt(coors[0]);
        var top = parseInt(coors[3]);
        $(this).css('width', parseInt(coors[2]) - left);
        $(this).css('height', top - parseInt(coors[1]));
        w2d.fillStyle = "black";

        if (parseInt(u) == 1) {
            w2d.fillStyle = '#a446a4';
        } else if (type != 1) {
            var l = points.length * 0.1;
            var h = points.length * 0.9;
            for (var i = 0; i < points.length; i++) {
                if (i > l && i < h)
                    continue;
                if (txt == points[i].str) {
                    if (i <= l) {
                        w2d.fillStyle = 'red';
                    } else {
                        w2d.fillStyle = 'blue';
                    }
                }
            }
        }
        w2d.font = "12px verdana";
        $(this).attr('fill', w2d.fillStyle);
        if (wordsAnnMap[txt] != null) {
            var idx = wordsMap[txt];
            w2d.fillText(wordsInfo[idx].ANList[0] + '(' + wordsInfo[idx].TopFourAnCntList[0] + ')', left, top);
            $(this).attr('filltext', wordsInfo[idx].ANList[0] + '(' + wordsInfo[idx].TopFourAnCntList[0] + ')');
        }
        else {
            var ftxt = txt;
            if (freq != '0')
                ftxt = txt + '.' + freq;
            w2d.fillText(ftxt, left, top);
            $(this).attr('filltext', ftxt);
        }
        var left = left + w2d.measureText($(this).attr('filltext')).width;
        var an1 = $(this).attr('an1');
        var an2str = $(this).attr('an2');
        w2d.save();
        if (an1 != null) {
            an1 = parseInt(an1);
            var an2 = 0;
            if (an2str != null)
                an2 = parseInt(an2str);
            var bkstyle = 'rgba(255,255,255,1.0)';
            var zero = false;
            if (an1 == 0) {
                bkstyle = 'rgb(0,128,64)';
                zero = true;
            }
            else if (an2str != null && an2 == 0) {
                bkstyle = 'rgb(128,0,255)';
                zero = true;
            }
            w2d.fillStyle = bkstyle;
            w2d.fillRect(left, parseInt(coors[1]), w2d.measureText('.' + Math.abs(an1 >> 1)).width, top - parseInt(coors[1]));
            if (zero)
                w2d.fillStyle = 'white';
            else
                w2d.fillStyle = 'rgb(128,0,255)';
            if ((an1 & 0x1) == 1)
                w2d.font = "italic 12px verdana";
            w2d.fillText('.' + Math.abs(an1 >> 1), left, top);
            left = left + w2d.measureText('.' + Math.abs(an1 >> 1)).width;
            w2d.fillStyle = bkstyle;
            if (an2str != null) {
                w2d.fillRect(left, parseInt(coors[1]), w2d.measureText('.' + Math.abs(an2 >> 1)).width, top - parseInt(coors[1]));
                if (zero)
                    w2d.fillStyle = 'white';
                else
                    w2d.fillStyle = 'rgb(0,128,64)';
                if ((an2 & 0x1) == 1)
                    w2d.font = "italic 12px verdana";
                else
                    w2d.font = "12px verdana";
                w2d.fillText('.' + Math.abs(an2 >> 1), left, top);
            }

        }
        w2d.restore();
    });
    //$('#canvas-img')[0].src = $('#canvas-bk0')[0].toDataURL('images/png');
    $('#canvas-img')[0].src = $('#canvas-bk0')[0].toDataURL('images/png');
    // 热区点击事件
    $("#map area").on("click", function (e) {
        e.preventDefault();
        var keywords =  $(this).attr('title');
        window.parent.mapKeywords(keywords)
        // window.parent.postMessage({'action':'mapAction','mapKey':keywords},"*");
        window.parent.loading(true)
        // 国内相关公司列表
        $.ajax({
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json;charset=utf-8',
            url: api + 'companytrade/patent/list',
            data: JSON.stringify({
                dataType: "sql",
                foo: "SEARCH-MASTER",
                idi: "4",
                scontent: "ann%20%↵data%ct%",
                sf: "QueryFulltextAnalysis",
                showType: "second",
                sl: "chs",
                sq:  'R/'+keywords+' AND ns/中国 AND ANTYPE/企业 and top/400',
                sx: "cn/queryrelated-searchmaster_cn"
            }),
            beforeSend: function(request){
                request.setRequestHeader("Authorization", token)
            },
            success: function (res) {
                if(res.status==40301){
                    window.parent.vueStatus(res.status)
                    return
                }
                window.parent.vueCnMapList(res.data.sResult.data)
            },
            
        });
        // 国外相关公司列表
        $.ajax({
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json;charset=utf-8',
            url: api + 'companytrade/patent/list',
            data: JSON.stringify({
                dataType: "sql",
                foo: "SEARCH-MASTER",
                idi: "274766528119",
                scontent: "ann%20%↵data%ct%",
                sf: "QueryFulltextAnalysis",
                showType: "second",
                sl: "chs",
                sq:  'R/'+keywords+' AND not ns/中国 AND ANTYPE/企业 and top/400',
                sx: "cn/queryrelated-searchmaster_cn"
            }),
            beforeSend: function(request){
                request.setRequestHeader("Authorization", token)
            },
            success: function (res) {
                if(res.status==40301){
                    window.parent.vueStatus(res.status)
                    return
                }
                window.parent.vueEnMapList(res.data.sResult.data)
            },
            
        });

        // if (source=='1') {
        //     window.location = "./map.html?keyword=" + keywords + "&api=" + api + "&source=1";
        // }else{
        //     window.location = "./map.html?keyword=" + keywords + "&api=" + api
        // }
    });
    // 右击事件
    document.oncontextmenu = function() {
        return false;
    }
    $("#map area").mousedown(function(e){
        e.preventDefault()
        var keywords =  $(this).attr('title');
        if(e.which==3){
            window.parent.vueCurrentList(keywords)
        }
    })
}

function Hue2RGB(v1, v2, vH) {
    if (vH < 0) vH += 1;
    if (vH > 1) vH -= 1;
    if (6.0 * vH < 1) return v1 + (v2 - v1) * 6.0 * vH;
    if (2.0 * vH < 1) return v2;
    if (3.0 * vH < 2) return v1 + (v2 - v1) * ((2.0 / 3.0) - vH) * 6.0;
    return (v1);
}

function HSL2RGB(H, S, L) {
    var h, s, l;
    // h = H / 240.0;
    // s = S / 240.0;
    // l = L / 240.0;
    // return HSL2RGB2(h, s, l);
    h = H / 225.0;
    s = S / 225.0;
    l = L / 225.0;
    return HSL2RGB2(h, s, l);
}
function HSL2RGB2(H, S, L) {
    var R, G, B;
    var var_1, var_2;
    if (S == 0)                       //HSL values = 0 ÷ 1
    {
        R = L * 255.0;                   //RGB results = 0 ÷ 255
        G = L * 255.0;
        B = L * 255.0;
    }
    else {
        if (L < 0.5) var_2 = L * (1 + S);
        else var_2 = (L + S) - (S * L);

        var_1 = 2.0 * L - var_2;

        R = 255.0 * Hue2RGB(var_1, var_2, H + (1.0 / 3.0));
        G = 255.0 * Hue2RGB(var_1, var_2, H);
        B = 255.0 * Hue2RGB(var_1, var_2, H - (1.0 / 3.0));
    }
    return "rgb(" + Math.floor(R) + "," + Math.floor(G) + "," + Math.floor(B) + ")";
}
// 蓝色底
function GetColor(i) {
    var ret = new Array();
    var h = new Array(155, 192, 118, 26);
    var s = new Array(251, 200, 204, 207);
    //StringBuilder ret = new StringBuilder();
    var j, l, d;
    // var c0 = new Array('rgb(81,145,247)', 'rgb(81,145,247)', 'rgb(81,145,247)', 'rgb(81,145,247)');
    var c0 = new Array('rgb(100,145,200)', 'rgb(100,145,200)', 'rgb(100,145,200)', 'rgb(100,145,200)');
    // var c0 = new Array('rgb(233,237,253)', 'rgb(233,237,253)', 'rgb(233,237,253)', 'rgb(233,237,253)');
    // var c0 = new Array('rgb(254,254,254)', 'rgb(254,254,254)', 'rgb(254,254,254)', 'rgb(254,254,254)');
    ret.push(c0[i]);
    if (i == 0) {
        l = 223;
        d = 12;
    }
    else {
        l = 160;
        d = 12;
    }
    for (j = 0; j < 9; j++)
        ret.push(HSL2RGB(h[i], s[i], l - d * j));
    return ret;
}

// 黄色底
// function GetColor(i) {

//     var ret = new Array();
//     var h = new Array(40, 192, 118, 26);
//     var s = new Array(240, 200, 204, 207);
//     //StringBuilder ret = new StringBuilder();
//     var j, l, d;
//     var c0 = new Array('rgb(0,200,0)', 'rgb(0,200,0)', 'rgb(0,200,0)', 'rgb(0,200,0)');
//     ret.push(c0[i]);
//     if (i == 0) {
//         l = 120;
//         d = 12;
//     }
//     else {
//         l = 160;
//         d = 12;
//     }
//     for (j = 0; j < 9; j++)
//         ret.push(HSL2RGB(h[i], s[i], l - d * j));
//     return ret;
// }
function getAppendLength(ctx) {
    return ctx.measureText('.9999').width;
}
function getStringLengh(ctx, s) {
    return ctx.measureText('.9999' + s + '.9999').width;
}
var bitMask;
function goodPosition(x, y, w, h) {
    for (var i = y; i < y + h; i++) {
        for (var j = x; j < bitMask[i].length && j < x + w; j++) {
            if (bitMask[i][j] == 1)
                return false;
        }
    }
    return true;
}
function setMask(x, y, w, h) {
    for (var i = 0; i < h; i++) {
        for (var j = 0; j < w; j++)
            bitMask[y + i][j + x] = 1;
    }
}
function reCalcPosition(x, y, w, h, newPosition) {
    newPosition[0] = x;
    newPosition[1] = y;
    if (goodPosition(x, y, w, h)) {
        setMask(x, y, w, h);
        return true;
    }
    var y1 = y;
    var delta = 99999999;
    while (y1 > 1) {
        y1--;
        if (goodPosition(x, y1, w, h)) {
            newPosition[1] = y1;
            delta = y - y1;
            break;
        }
    }
    y1 = y;
    while (y1 + h < ih - 1) {
        y1++;
        if (y1 - y >= delta)
            break;
        if (goodPosition(x, y1, w, h)) {
            if (y1 - y < delta) {
                newPosition[1] = y1;
                delta = y1 - y;
                break;
            }
        }
    }
    var x1 = x;
    while (x1 > 1) {
        x1--;
        if (x - x1 >= delta)
            break;
        if (goodPosition(x1, y, w, h)) {
            if (x - x1 < delta) {
                newPosition[0] = x1;
                delta = x - x1;
            }
            break;
        }
    }
    x1 = x;
    while (x1 + w < iw - 1) {
        x1++;
        if (x1 - x >= delta)
            break;
        if (goodPosition(x1, y, w, h)) {
            if (x1 - x < delta) {
                newPosition[0] = x1;
                delta = x1 - x;
                break;
            }
        }
    }
    setMask(newPosition[0], newPosition[1], w, h);
    return true;
}

function drawBackGround(ctx, ctm) {
    $('#patentmap').empty();
    $('#map').empty();
    ctx.clearRect(0, 0, ctx.width, ctx.height);

    ctx.drawImage($('#bk')[0], 0, 0);
    if (ctm.tag != null && ctm.TagFreq != null && ctm.tag.length == ctm.TagFreq.length) {
        for (var i = 0; i < ctm.tag.length; i++) {
            ctm.tag[i] = ctm.tag[i] + '.' + ctm.TagFreq[i];
        }
    }
    var appendArea = true;
    if ($('.area').length > 0)
        appendArea = false;
    bitMask = new Array();
    ih = parseInt(ih);
    iw = parseInt(iw);
    for (var i = 0; i < ih + 132; i++) {
        bitMask[i] = new Array();
    }
    var PAINT_SIZE = 2;
    var C_TERM = 128;
    var FONT_SIZE = 14;
    // var p_clr = new Array('#ff0000', '#ff00ff', '#00ff00', '#000080',
    // 						   '#ff8040', '#00ffff', '#008000', '#a0522d', '#000000');
    var p_clr = new Array('#ff0000', '#ff00ff', '#00ff00', '#000080',
        '#ff8040', '#00ffff', '#008000', '#a0522d', '#000000');
    var width = iw - PAINT_SIZE * 2; //paramiw - PAINT_SIZE*2;;
    var height = ih - PAINT_SIZE * 2; //paramih - PAINT_SIZE*2;
    //g.setColor(new Color(0xe2ebed));
    //double s = (height+PAINT_SIZE*2) / Math.sqrt((height+PAINT_SIZE*2)*(height+PAINT_SIZE*2) + (width+PAINT_SIZE*2)*(width+PAINT_SIZE*2));
    //g.setColor(new Color(0xe2ebed));
    //g.setFont(new Font("verdana", Font.PLAIN, FONT_SIZE));
    ctx.font = "12px verdana";
    var end, begin, nc;
    var xmax, ymax, xmin, ymin;
    var tags = new Array();
    var userWord = new Array();
    xmax = ymax = -100000;
    xmin = ymin = 100000000;
    var l1 = 0;
    var l2 = 0;
    if (ctm.pns != null)
        l1 = ctm.pns.length;
    if (ctm.tag != null)
        l2 = ctm.tag.length;
    for (var i = 0; i < l1; i++) {
        tags.push(ctm.pns[i]);
        userWord.push(0);
    }
    
    for (var j = 0; j < l2; j++) {
        tags.push(ctm.tag[j]);
        userWord.push(ctm.u[j]);
    }
    end = 0;
    for (var j = 0; j < Math.floor(ctm.coor[0]); j++) {
        begin = end + 2;
        end = Math.floor(ctm.coor[end + 1]);
        for (var i = begin + 1; i <= end; i += 2) {
            if (xmax < ctm.coor[i])
                xmax = ctm.coor[i];
            if (xmin > ctm.coor[i])
                xmin = ctm.coor[i];
            if (ymax < ctm.coor[i + 1])
                ymax = ctm.coor[i + 1];
            if (ymin > ctm.coor[i + 1])
                ymin = ctm.coor[i + 1];
        }
    }
    for (var i = end + 1; i < end + 1 + ctm.num * 2; i += 2) {
        if (xmax < ctm.coor[i])
            xmax = ctm.coor[i];
        if (xmin > ctm.coor[i])
            xmin = ctm.coor[i];
        if (ymax < ctm.coor[i + 1])
            ymax = ctm.coor[i + 1];
        if (ymin > ctm.coor[i + 1])
            ymin = ctm.coor[i + 1];
    }

    var scalex = width / (xmax - xmin);
    var scaley = height / (ymax - ymin);
    var x, y;

    end = 0;
    nc = Math.floor(ctm.coor[0]);
    var i;
    var clr = GetColor(ifill);
    // Color shapeColor = null;
    try {
        
        // g.setStroke(new BasicStroke(2.0f));
        var x0, y0, x1, y1;
        x0 = 0;
        x1 = 1000000;
        y0 = 0;
        y1 = 1000000;
        ctx.lineWidth = 3;
        for (var j = 0; j < nc; j++) {
            var colorindex = Math.floor(ctm.coor[end + 2]);
            
            //shapeColor = new Color(clr[(int)ctm.returncoor[end+2]]);
            begin = end + 3;
            end = Math.floor(ctm.coor[end + 1]);
            x = (-xmin + ctm.coor[begin]) * scalex + PAINT_SIZE;
            y = (ymax - ctm.coor[begin + 1]) * scaley + PAINT_SIZE;
            
            ctx.beginPath();
            ctx.strokeStyle = 'white';
            ctx.moveTo(x, y);
            x0 = x;
            x1 = x;
            y0 = y;
            y1 = y;
            for (i = begin + 2; i <= end; i += 2) {
                x = (-xmin + ctm.coor[i]) * scalex + PAINT_SIZE;
                y = (ymax - ctm.coor[i + 1]) * scaley + PAINT_SIZE;
                if (x < x0)
                    x0 = x;
                if (x > x1)
                    x1 = x;
                if (y < y0)
                    y0 = y;
                if (y > y1)
                    y1 = y;
                ctx.lineTo(x, y);
            }
            ctx.stroke();
            var radius = Math.max(x1 - x0, y1 - y0) / 2;
            
            if (radius > 0) {
                var grd = ctx.createRadialGradient((x0 + x1) / 2, (y0 + y1) / 2, radius / 50, (x0 + x1) / 2, (y0 + y1) / 2, radius);
                
                if (colorindex == 0) {
                    grd.addColorStop(0, clr[0]);
                    grd.addColorStop(1, "rgba(100,145,255,0.5)");
                }
                else if (colorindex == 1) {
                    grd.addColorStop(0, clr[1]);
                    grd.addColorStop(1, clr[0]);
                }
                else {
                    grd.addColorStop(0, clr[colorindex > 0 ? colorindex - 1 : colorindex]);
                    grd.addColorStop(1, clr[colorindex]);
                }
                ctx.fillStyle = grd;
                ctx.fill();
                ctx.closePath();
            }
            
        }
        var ic, ip;
        ic = ip = 0;
        var shapeColor = p_clr[0];
        var tempColor = p_clr[0];
        var tagindex = 0; //CLASTER_COUNT;
        var coor = new Array();
        var cindex = 0; //CLASTER_COUNT;
        for (var i = 1; i < ctm.cln.length; i++) {
            ctm.cln[i] += ctm.cln[i - 1];
        }
        var pntagsx = new Array(); //float[ctm.returncln.length*2];
        var pntagsy = new Array(); //new float[ctm.returncln.length*2];
        var pnlen = 0;
        if (ctm.pns != null)
            pnlen = ctm.pns.length;
        for (var i = 0; i < ctm.cln.length * 2; i++) {
            pntagsx[i] = 0;
            pntagsy[i] = 0;
        }
        for (i = end + 1; i < end + 1 + C_TERM * 2 * 2; i += 2) {
            if (cindex >= tags.length) {
                break;
            }
            if (i + 1 >= ctm.coor.length)
                break;
            if (ic < ctm.cln.length && cindex == (ctm.cln[ic] - 1)) {
                ic++;
                shapeColor = p_clr[ic];
                tempColor = p_clr[ic];
                //g.setColor(shapeColor);
            }
            ip++;
            x = (-xmin + ctm.coor[i]) * scalex + PAINT_SIZE;
            y = (ymax - ctm.coor[i + 1]) * scaley + PAINT_SIZE;
            pntagsx[ic] += x;
            pntagsy[ic] += y;
            /*ctx.beginPath();
             ctx.strokeStyle = shapeColor;
             ctx.arc(x-2.0,y+2.0,2.0,0,Math.PI*2,true);
             ctx.stroke();
             ctx.fillStyle='white';
             ctx.fill();
             ctx.closePath();
             */
            var ax = x;
            var ay = y;
            ctx.strokeStyle = '#000000';
            var len = getStringLengh(ctx, tags[tagindex]);
            x -= len / 2;
            if (x < 0)
                x = 0;
            if (tags[tagindex].indexOf('air') == 0) {
                var cdd = 0;
            }
            reCalcPosition(Math.floor(x), Math.floor(y), Math.floor(len), wordHeight, coor);
            x = coor[0] + getAppendLength(ctx);
            y = coor[1];
            var lidx = tags[tagindex].lastIndexOf('.');
            var word = tags[tagindex];
            var freq = 0;
            if (lidx != -1) {
                freq = word.substring(lidx + 1);
                word = word.substring(0, lidx);
            }
            len -= getAppendLength(ctx) * 2;
            if (appendArea) {
                $('#map').append($('<area shape="rect" coords="' + (ax - len / 2) + ',' + (ay - wordHeight / 2) + ',' + (ax + len / 2) + ',' + (ay + wordHeight / 2) + '" href ="sun.html" alt="' + word + '" title="' + word + '"/>'));
                $('#patentmap').append($('<div ax="' + ax + '" ay="' + ay + '" ac="' + shapeColor + '" class="area" onmouseover="onPatentMapMouseOver(this, event)" onmouseout="onPatentMapMouseOut(this, event)" style="width:' + len + 'px;height:' + wordHeight + 'px;left: ' + x + 'px; top: ' + (y - wordHeight + 16) + 'px;" onclick="newMap(this);" coords="' + x + ',' + (y - wordHeight) + ',' + (x + len) + ',' + y + '" w="' + word + '" c="' + freq + '" u="' + userWord[tagindex] + '"></div>'));
            }
            //ctx.fillStyle="black";
            //ctx.fillText(tags[tagindex], x, y);
            tagindex++; //g.drawString(tags[tagindex++], x, y);
            cindex++;
        }
        if (ctm.pns != null && ctm.pns.length > 0) {
            for (var ci = 0; ci < ctm.cln.length; ci++) {
                var ccnt = ctm.cln[ci];
                if (ci > 0)
                    ccnt = ccnt - ctm.cln[ci - 1];
                if (ccnt > 0) {
                    pntagsx[ci] /= ccnt;
                    pntagsy[ci] /= ccnt;
                    //g.setColor(new Color(0x0000ff));

                    x = pntagsx[ci];
                    y = pntagsy[ci];
                    //shapeColor=new Color(p_clr[ci]);
                    tempColor = p_clr[ci];
                    //g.setColor(shapeColor);

                    /*Ellipse2D.Float ellipse_shape= new Ellipse2D.Float(x-2.0f,y+2.0f,4.0f,4.0f);
                     g.draw(ellipse_shape);
                     g.fill(ellipse_shape);
                     */
                    var ax = x;
                    var ay = y;
                    var ac = p_clr[ci];
                    //g.setColor(new Color(0xff0000));


                    if (x + tags[tagindex].length * FONT_SIZE > width)
                        x = width - tags[tagindex].length * FONT_SIZE - FONT_SIZE;
                    if (y - FONT_SIZE <= 0)
                        y = FONT_SIZE * 2;
                    var len = getStringLengh(ctx, tags[tagindex]);
                    x -= len / 2;
                    if (x < 0)
                        x = 0;
                    reCalcPosition(Math.floor(x), Math.floor(y), Math.floor(len), wordHeight, coor);
                    x = coor[0] + getAppendLength(ctx);
                    y = coor[1];
                    var lidx = tags[tagindex].lastIndexOf('.');
                    var word = tags[tagindex];
                    var freq = 0;
                    if (lidx != -1) {
                        freq = word.substring(lidx + 1);
                        word = word.substring(0, lidx);
                    }
                    $('#map').append($('<area shape="rect" coords="' + (ax - len / 2) + ',' + (ay - wordHeight / 2) + ',' + (ax + len / 2) + ',' + (ay + wordHeight / 2) + '" href ="sun.html" alt="' + word + '" title="' + word + '"/>'));

                    $('#patentmap').append($('<div ax="' + ax + '" ay="' + ay + '" ac="' + ac + '" class="area" onmouseover="onPatentMapMouseOver(this, event)" onmouseout="onPatentMapMouseOut(this, event)" style="width:' + len + 'px;height:' + wordHeight + 'px;left: ' + x + 'px; top: ' + (y - wordHeight + 16) + 'px;" onclick="newMap(this);" coords="' + x + ',' + (y - wordHeight) + ',' + (x + len) + ',' + y + '" w="' + word + '" c="' + freq + '" u="' + userWord[tagindex] + '"></div>'));

                    //returnMaps[tagindex] = new ImageMapElement(x,y-wordHeight,(int)(x+len),y,tags[tagindex],0,0);
                    /* if(userWords.contains(returnMaps[tagindex].query))
                     returnMaps[tagindex].setUserWords(1);
                     if(paramsjpg.equalsIgnoreCase("on"))
                     g.drawString(tags[tagindex], x, y);*/
                    tagindex++; //g.drawString(tags[tagindex++], x, y);
                }
            }
        }
    } catch (e) { console.log(e); }

}